import React, { Component } from 'react';
import { base, toast } from 'nc-lightapp-front';
// import proFetch from '../../../../public/functions/project-fetch';
import {hrAjax as ajax} from 'src/hrpub/common/utils/utils';
const { NCModal, NCButton, NCCheckbox, NCRadio} = base;
const { Header: NCModalHeader, Body: NCModalBody, Footer: NCModalFooter } = NCModal;
import AOSOrgRef from '../../../../../hrjf/refer/jfref/AOSOrgRefMo';
import AOSDeptRef from '../../../../../hrjf/refer/jfref/AOSDeptRefMo';
import './index.less';

class ManageScopeSet extends Component {
    constructor(props) {
        super(props);
        this.confirmModal = this.confirmModal.bind(this);
        this.closeModal = this.closeModal.bind(this);
        this.onChangeHandle = this.onChangeHandle.bind(this);
        this.deleteData = this.deleteData.bind(this);
        this.clearData = this.clearData.bind(this);
        this.openNcModal = this.openNcModal.bind(this);
        this.sureAddFun = this.sureAddFun.bind(this);
        this.orgRefChange = this.orgRefChange.bind(this);
        this.deptRefChange = this.deptRefChange.bind(this);
        this.refChangeFun = this.refChangeFun.bind(this);
        this.selectOrgRefer = this.selectOrgRefer.bind(this);
        this.selectDeptRefer = this.selectDeptRefer.bind(this);
        this.state = {
            hrChecked: true,//人事管理checkbox
            contractChecked: true,//合同管理checkbox
            salaryChecked: true,//薪酬管理checkbox
            selectedValue:'orgValue',
            activeKey: 1,//table的key
            orgRef:'',
            deptRef:'',
            language: {}
        }
    }
    componentDidMount() {

    }
    // 获取父组件的多语词条
    getLanguage (language) {
        this.setState({
            language: language
        })
    }
    openNcModal() {//开始显示时的钩子函数
        this.props.form.setFormStatus('card3', 'edit');
        this.clearData()
    }
    confirmModal() {
        let searchResultData = this.state.activeKey == 1 ? this.props.editTable.getAllRows('orglist') : this.props.editTable.getAllRows('deptlist');
        let hrOrg = this.props.form.getAllFormValue('card3');
        if (hrOrg.rows[0].values.target.value){
            if (searchResultData.length) {
                this.sureAddFun()
            } else {
                toast({
                    color: 'warning',
                    content: this.state.language['hi6007-000254'] // 请增加“管理对象”！
                });
            }
        }else{
            toast({
                color: 'warning',
                content: this.state.language['hi6007-000255'] // 请选择“人力资源组织”！
            })
        }

    }
    sureAddFun() {
        let searchResultData = this.state.activeKey == 1 ? this.props.editTable.getAllRows('orglist') : this.props.editTable.getAllRows('deptlist');
        let hrOrg = this.props.form.getAllFormValue('card3');
        let managescopeBusiRegions = [], pk_psndoc = [];
        searchResultData && searchResultData.forEach((v, k) => {
            if (this.state.activeKey == 1 ){
                pk_psndoc.push(v.values.pk_org.value)
            }else{
                pk_psndoc.push(v.values.pk_dept.value)
            }
        })
        if (this.state.hrChecked) {
            managescopeBusiRegions.push('PSNDOC00000000000000')
        }
        if (this.state.contractChecked) {
            managescopeBusiRegions.push('PSNPACT0000000000000')
        }
        if (this.state.salaryChecked) {
            managescopeBusiRegions.push('SALARY00000000000000')
        }
        let postData = {
            manageScopeType: 'manage_scope_type_org',
            managescopeBusiRegions: managescopeBusiRegions,//管理业务范围
            pk_keypsn_group: '',//关键人员组主键
            pk_org_dept: pk_psndoc,
            pk_orgs: hrOrg.rows[0].values.target.value,//人力资源组织主键
            selectManageScope: this.state.selectedValue == 'orgValue' ? 'org' :'dept',//组织org、部门dept、人员psn
            funcType:1//组织
        };
        ajax({
            url: '/nccloud/hrjf/managescope/AddManageScopeAction.do',
            body: postData,
        }).then((res) => {
            if (res.success) {
                this.closeModal();
                this.props.updateMainTableData(res.data.managescopelist, 1, 'add')
            }
        });
    }
    closeModal() {
        this.props.onClose && this.props.onClose();
    }
    deleteData(){//删除
        if (this.state.activeKey == 1){
            let selectData = this.props.editTable.getCheckedRows('orglist') || [];
            let deleteDataIndex = [];
            if (selectData.length) {
                selectData.forEach((v, k) => {
                    deleteDataIndex.push(v.index)
                })
                this.props.editTable.deleteTableRowsByIndex('orglist', deleteDataIndex, true);
                this.orgRefChange();
            } else {
                toast({
                    color: 'warning',
                    content: this.state.language['hi6007-000256'] // 请选择要删除的管理对象！
                });
            }
        }else{
            let selectData = this.props.editTable.getCheckedRows('deptlist') || [];
            let deleteDataIndex = [];
            if (selectData.length) {
                selectData.forEach((v, k) => {
                    deleteDataIndex.push(v.index)
                })
                this.props.editTable.deleteTableRowsByIndex('deptlist', deleteDataIndex, true);
                this.deptRefChange();
            } else {
                toast({
                    color: 'warning',
                    content: this.state.language['hi6007-000256'] // 请选择要删除的管理对象！
                });
            }
        }

    }
    clearData(){//清空表格
        if (this.state.activeKey==1){
            this.props.editTable.setTableData('orglist', { rows: [] })
            this.orgRefChange();
        }else{
            this.props.editTable.setTableData('deptlist', { rows: [] })
            this.deptRefChange();
        }
    }
    onChangeHandle(type){
        return (value) => {
            this.setState({
                [type]: value,
            });
            if (type == 'selectedValue'){
                this.setState({
                    activeKey: value == 'orgValue' ? 1 : 2
                });
            }
        }
    }
    orgRefChange(value){
        this.setState({
            orgRef: value
        })
        this.refChangeFun(value)
    }
    deptRefChange(value){
        this.setState({
            deptRef: value
        })
        this.refChangeFun(value)
    }
    selectOrgRefer(){
        this.setState({
            orgRef: ''
        })
    }
    selectDeptRefer(){
        this.setState({
            deptRef: ''
        })
    }
    refChangeFun(value){
        let refResultData = this.state.activeKey == 1 ? this.props.editTable.getAllRows('orglist') : this.props.editTable.getAllRows('deptlist');
        let new_pks = [], old_pks = [], historyData = [];
        value && value.forEach((v, k) => {
            new_pks.push(v.refpk)
        })

        refResultData.forEach((v, k) => {
            if (this.state.activeKey == 1) {
                old_pks.push(v.values.pk_org.value)
            }else{
                old_pks.push(v.values.pk_dept.value)
            }

        })
        let postData = {
            new_pks: new_pks,
            old_pks: old_pks,
            selectManageScope: this.state.activeKey == 1 ? 'org' : 'dept'
        };
        ajax({
            url: '/nccloud/hrjf/managescope/ManageScopeGetVoFromRefer.do',
            body: postData,
        }).then((res) => {
            if (res.success) {
                if (this.state.activeKey == 1) {
                    if (res.data && res.data.orglist) {
                        historyData = res.data.orglist;
                        let newData = JSON.parse(JSON.stringify(historyData))
                        newData.rows = refResultData.concat(historyData.rows)
                        this.props.editTable.setTableData('orglist', newData)
                    }
                } else {
                    if (res.data.deptlist) {
                        historyData = res.data.deptlist;
                        let newData = JSON.parse(JSON.stringify(historyData))
                        newData.rows = refResultData.concat(historyData.rows)
                        this.props.editTable.setTableData('deptlist', newData)

                    }

                }



            }
        });
    }
    render() {
        const {
            form,
            editTable,
            visible
        } = this.props;

        const {
            activeKey,
            hrChecked,
            contractChecked,
            salaryChecked,
            selectedValue,
            orgRef,
            deptRef
        } = this.state;
        return (
            <NCModal
                show={visible}
                size="xlg"
                className="manage-scope-set"
                onHide={this.closeModal}
                backdrop={'static'}
                onEnter={this.openNcModal}
            >
                {/* 组织管理范围设置 */}
                <NCModalHeader closeButton={true}>
                    {this.state.language['hi6007-000257']}
                </NCModalHeader>
                <NCModalBody>
                    <div className="form-wrapper">
                        {form.createForm('card3', {
                            //编辑后事件
                        })}
                    </div>
                    <div className="checkbox-content">
                        {/* 管理业务范围 */}
                        <span className="checkbox-title">{this.state.language['hi6007-000258']}</span>
                        {/* 人事管理 */}
                        <NCCheckbox
                            className="header-checkbox"
                            color="primary"
                            onChange={this.onChangeHandle('hrChecked')}
                            checked={hrChecked}
                        >
                            {this.state.language['hi6007-000259']}
                        </NCCheckbox>
                        {/* 合同管理 */}
                        <NCCheckbox
                            className="header-checkbox"
                            color="primary"
                            onChange={this.onChangeHandle('contractChecked')}
                            checked={contractChecked}
                        >
                            {this.state.language['hi6007-000260']}
                        </NCCheckbox>
                        {/* 薪酬管理 */}
                        <NCCheckbox
                            className="header-checkbox"
                            color="primary"
                            onChange={this.onChangeHandle('salaryChecked')}
                            checked={salaryChecked}
                        >
                            {this.state.language['hi6007-000261']}
                        </NCCheckbox>
                    </div>
                    <div className="radio-content">
                        {/* 管理范围设置 */}
                        <span className="radio-title">{this.state.language['hi6007-000252']}</span>
                        <NCRadio.NCRadioGroup
                            name="manageScope"
                            selectedValue={selectedValue}
                            onChange={this.onChangeHandle('selectedValue')}>
                            {/* 按组织设置 */}
                            <NCRadio value="orgValue" >{this.state.language['hi6007-000262']}</NCRadio>
                            {/* 按部门设置 */}
                            <NCRadio value="deptValue" >{this.state.language['hi6007-000263']}</NCRadio>
                        </NCRadio.NCRadioGroup>

                    </div>
                    <div className="operation-button-wrapper">
                        <div className="operation-button">
                            <span className="refer-wrapper"
                            >
                                {/* 参照选择 */}
                                { activeKey==1&&
                                    <AOSOrgRef className="org-ref"
                                        value={orgRef}
                                        onChange={this.orgRefChange}
                                        clickContainer={<NCButton shape="border"
                                            onClick={this.selectOrgRefer}
                                        >
                                            {this.state.language['hi6007-000264']}
                                    </NCButton>}
                                    />
                                }
                                {/* 参照选择 */}
                                {
                                    activeKey == 2 &&
                                    <AOSDeptRef className="dept-ref"
                                        value={deptRef}
                                        onChange={this.deptRefChange}
                                        clickContainer={<NCButton shape="border"
                                            onClick={this.selectDeptRefer}
                                        >
                                            {this.state.language['hi6007-000264']}
                                    </NCButton>}
                                    />
                                }

                            </span>
                            <span className="button-options">
                                {/* 删除 */}
                                <NCButton shape="border"
                                    onClick={this.deleteData}>
                                    {this.state.language['hi6007-000031']}
                                </NCButton>
                                {/* 清空 */}
                                <NCButton
                                    shape="border"
                                    onClick={this.clearData}
                                >
                                    {this.state.language['hi6007-000084']}
                                </NCButton>
                            </span>

                        </div>
                    </div>
                    {   activeKey == 1 &&
                        editTable.createEditTable('orglist', {
                            showCheck: true,
                            showIndex: true,
                        })
                    }
                    {
                        activeKey == 2 &&
                        editTable.createEditTable('deptlist', {
                            showCheck: true,
                            showIndex: true,
                        })
                    }

                </NCModalBody>
                <NCModalFooter>
                    {/* 确定 */}
                    <NCButton colors="primary"
                        onClick={this.confirmModal}>
                        {this.state.language['hi6007-000004']}
                    </NCButton>
                    {/* 取消 */}
                    <NCButton
                        shape="border"
                        onClick={this.closeModal}
                    >
                        {this.state.language['hi6007-000005']}
                    </NCButton>
                </NCModalFooter>
            </NCModal>
        );
    }
}

export default ManageScopeSet;
